/**
 * 步骤4测试：身份验证（onClickContinue提交，处理电话/办事处分支）
 */

import { fileURLToPath } from 'node:url'
import { dirname, join } from 'node:path'
import { HttpSession } from '../src/main/request/http-session'
import { getPageParser } from '../src/main/automation/page-parser'
import { loadConfig } from '../src/main/config/index'
import { setupLogger } from '../src/main/logger/index'
import { writeFile, mkdir, readFile } from 'node:fs/promises'

const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
const projectRoot = join(__dirname, '..')

const BASE_URL = 'https://abs1.td.gov.hk/tdab2/tdabs_external/AdminServlet_tchinese'
const SNAPSHOT_DIR = join(projectRoot, 'test-steps-snapshots')

async function saveSnapshot(name: string, html: string, metadata: any = {}) {
  await mkdir(SNAPSHOT_DIR, { recursive: true })
  const timestamp = new Date().toISOString().replace(/[:.]/g, '-')
  const filename = `${timestamp}_step04_${name}.html`
  const filepath = join(SNAPSHOT_DIR, filename)
  await writeFile(filepath, html, 'utf8')
  console.log(`  ✓ 快照已保存: ${filename}`)
  return filepath
}

async function loadStep3Result() {
  const files = await import('node:fs/promises')
  const dir = await files.readdir(SNAPSHOT_DIR)
  const step3Files = dir.filter(f => f.includes('step03_form_filled') && f.endsWith('.html')).sort().reverse()
  
  if (step3Files.length === 0) {
    throw new Error('未找到步骤3的快照文件，请先运行步骤3测试')
  }
  
  const latestFile = join(SNAPSHOT_DIR, step3Files[0])
  const html = await readFile(latestFile, 'utf8')
  const parser = getPageParser()
  const formFields = parser.extractFormFields(html, 'frmAppointment')
  
  return { html, formFields, filepath: latestFile }
}

function checkPage(html: string, stepName: string): { success: boolean, details: Record<string, boolean>, nextStep?: string } {
  const checks = {
    isIdentityCheck: html.includes('cmdCheckIdentifierAction'),
    isPhoneInput: html.includes('電話號碼') || html.includes('电话号码') || html.includes('txtPhoneNumber'),
    isOfficeSelect: html.includes('選擇牌照事務處') || html.includes('officeSelect') || html.includes('listLicenseCenter'),
    isCalendar: html.includes('cmdGetCalendarAction') || html.includes('onClickDate') || html.includes('calendar-table'),
    hasError: html.includes('系統繁忙') || html.includes('錯誤') || html.includes('512-E-'),
    hasForm: html.includes('form') && html.includes('frmAppointment'),
  }
  
  let nextStep: string | undefined
  if (checks.isCalendar) nextStep = 'calendar'
  else if (checks.isPhoneInput) nextStep = 'phone'
  else if (checks.isOfficeSelect) nextStep = 'office'
  
  console.log(`\n📄 页面检查: ${stepName}`)
  console.log('─'.repeat(60))
  for (const [key, value] of Object.entries(checks)) {
    const icon = value ? '✓' : '✗'
    const label = key.replace(/([A-Z])/g, ' $1').trim()
    console.log(`  ${icon} ${label}`)
  }
  
  const success = checks.hasForm && (checks.isPhoneInput || checks.isOfficeSelect || checks.isCalendar)
  return { success, details: checks, nextStep }
}

async function testStep4() {
  console.log('步骤4测试：身份验证（onClickContinue提交，处理电话/办事处分支）')
  console.log('='.repeat(60))
  
  await loadConfig()
  await setupLogger()
  
  // 加载步骤3的结果（表单填写完成状态）
  console.log('\n📂 加载步骤3结果...')
  const step3Result = await loadStep3Result()
  const step3Fields = step3Result.formFields.success && step3Result.formFields.data ? step3Result.formFields.data : {}
  console.log(`  从步骤3提取字段数: ${Object.keys(step3Fields).length}`)
  
  const session = new HttpSession()
  
  // 子步骤4.1: 提交身份验证（调用onClickContinue）
  console.log('\n子步骤4.1: 提交身份验证（onClickContinue -> cmdCheckIdentifierAction）')
  console.log('─'.repeat(60))
  
  const testData = {
    passport: 'CE2345678',
    license: '440123199012011234',
    name: '测试用户',
    email: 'test@example.com',
    issuingCountry: 'CN',
    issuingAuthority: 'GD',
  }
  
  // 构造提交表单（对齐onClickContinue DI分支的逻辑）
  const payload: Record<string, string> = {
    ...step3Fields,
    storedAppointmentOperation: 'A',
    storedAppointmentServiceType: 'DI',
    storedAppointmentLicenseType: 'P',
    storedAppointmentLicenseNumber: testData.passport,
    storedAppointmentLicenseNumber2: testData.license,
    storedAppointmentLicenseOwnerName: testData.name,
    storedAppointmentIssuingCountry: testData.issuingCountry,
    storedAppointmentIssuingAuthority: testData.issuingAuthority,
    storedAppointmentConfirmationEmail: testData.email,
    storedAppointmentReminderEmail: testData.email,
    storedAppointmentPhoneNumber: 'N/A',
    storedAppointmentExpiryDate: '11-11-1901',
    sendReminder: 'Y',
    inputType: 'N',
    transferOfOwnership: 'N',
    timestamp: Date.now().toString(),
  }
  
  const url = `${BASE_URL}?cmd=cmdCheckIdentifierAction`
  console.log(`请求: POST ${url}`)
  console.log(`  身份信息: ${testData.name} / ${testData.passport}`)
  console.log(`  载荷字段数: ${Object.keys(payload).length}`)
  
  const response = await session.postForm(url, payload, `${BASE_URL}?cmd=cmdInputPersonalInfo`)
  const check = checkPage(response.body, '身份验证响应')
  
  await saveSnapshot('identity_check', response.body, {
    step: '4.1',
    url: response.url,
    status: response.status,
    check,
    nextStep: check.nextStep,
  })
  
  if (!check.success) {
    console.log('\n❌ 子步骤4.1失败：未进入预期的下一步页面')
    process.exit(1)
  }
  
  const parser = getPageParser()
  let currentFields = parser.extractFormFields(response.body, 'frmAppointment')
  let currentHtml = response.body
  let currentUrl = response.url
  
  // 子步骤4.2: 处理电话填写分支（如果需要）
  if (check.nextStep === 'phone') {
    console.log('\n子步骤4.2: 处理电话填写分支')
    console.log('─'.repeat(60))
    
    // 使用有效的香港电话号码格式（8位数字，以2、3、5、6、8、9开头）
    const testPhone = '21234567'
    
    const baseFields = currentFields.success && currentFields.data ? currentFields.data : {}
    const phonePayload: Record<string, string> = {
      ...baseFields,
      storedAppointmentOperation: 'A',
      inputType: 'N',
      storedAppointmentPhoneNumber: testPhone,
      timestamp: Date.now().toString(),
    }
    
    console.log(`  电话号码: ${testPhone}`)
    
    const phoneResponse = await session.postForm(
      `${BASE_URL}?cmd=cmdCheckIdentifierAction`,
      phonePayload,
      currentUrl,
    )
    
    const phoneCheck = checkPage(phoneResponse.body, '电话填写响应')
    await saveSnapshot('phone_input', phoneResponse.body, {
      step: '4.2',
      url: phoneResponse.url,
      status: phoneResponse.status,
      check: phoneCheck,
      phone: testPhone,
      nextStep: phoneCheck.nextStep,
    })
    
    currentFields = parser.extractFormFields(phoneResponse.body, 'frmAppointment')
    currentHtml = phoneResponse.body
    currentUrl = phoneResponse.url
    
    if (!phoneCheck.success) {
      console.log('\n❌ 子步骤4.2失败：电话填写后未进入预期的下一步')
      process.exit(1)
    }
  }
  else {
    console.log('\n子步骤4.2: 跳过（不需要填写电话号码）')
  }
  
  // 子步骤4.3: 处理办事处选择分支（如果需要）
  const finalCheck = checkPage(currentHtml, '最终状态检查')
  if (finalCheck.nextStep === 'office') {
    console.log('\n子步骤4.3: 处理办事处选择分支')
    console.log('─'.repeat(60))
    
    const officeCode = 'HKLO'
    const baseFields = currentFields.success && currentFields.data ? currentFields.data : {}
    const officePayload: Record<string, string> = {
      ...baseFields,
      storedAppointmentOperation: 'A',
      storedAppointmentOfficeCode: officeCode,
      storedAppointmentServiceType: baseFields.storedAppointmentServiceType || 'DI',
      storedAppointmentRequestChannel: baseFields.storedAppointmentRequestChannel || 'W',
      timestamp: Date.now().toString(),
    }
    
    console.log(`  办事处: ${officeCode}`)
    
    const officeResponse = await session.postForm(
      `${BASE_URL}?cmd=cmdGetCalendarAction`,
      officePayload,
      currentUrl,
    )
    
    const officeCheck = checkPage(officeResponse.body, '办事处选择响应')
    await saveSnapshot('office_select', officeResponse.body, {
      step: '4.3',
      url: officeResponse.url,
      status: officeResponse.status,
      check: officeCheck,
      officeCode,
      nextStep: officeCheck.nextStep,
    })
    
    currentFields = parser.extractFormFields(officeResponse.body, 'frmAppointment')
    currentHtml = officeResponse.body
    currentUrl = officeResponse.url
    
    if (!officeCheck.success || officeCheck.nextStep !== 'calendar') {
      console.log('\n❌ 子步骤4.3失败：办事处选择后未进入日历页')
      process.exit(1)
    }
  }
  else {
    console.log('\n子步骤4.3: 跳过（不需要选择办事处）')
  }
  
  // 最终检查
  const finalStatusCheck = checkPage(currentHtml, '步骤4最终状态')
  if (finalStatusCheck.nextStep !== 'calendar') {
    console.log('\n❌ 步骤4失败：最终未到达日历页')
    process.exit(1)
  }
  
  console.log('\n✓ 步骤4成功：身份验证完成，已到达日历页')
  console.log(`\n📁 快照目录: ${SNAPSHOT_DIR}`)
}

testStep4().catch((error) => {
  console.error('\n❌ 测试失败:', error)
  process.exit(1)
})

